package com.zqx.tokenauth.handler;

import com.zqx.tokenauth.auth.CurrentUser;
import com.zqx.tokenauth.entity.User;
import com.zqx.tokenauth.enums.TokenEnum;
import com.zqx.tokenauth.repository.UserRepository;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 增加方法注入，将含有 CurrentUser 注解的方法参数注入当前登录用户
 * @author zqx
 * @date 2018.07.21
 */
@Component
@Slf4j
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        // 如果参数类型是 User 并且有 CurrentUser 注解则支持
        if (methodParameter.getParameterType ().isAssignableFrom (User.class) &&
                methodParameter.hasParameterAnnotation (CurrentUser.class)) {
            return true;

        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 取出鉴权时存入的登录用户 Id
        Long currentUserId = (Long) nativeWebRequest.getAttribute (TokenEnum.CURRENT_USER_ID.getMessage(), RequestAttributes.SCOPE_REQUEST);
        if (currentUserId != null) {
            // 从数据库中查询并返回
            log.info("【当前用户id为】,{}",currentUserId.toString());
            return userRepository.findById(currentUserId).get();
        }
        throw new MissingServletRequestPartException(TokenEnum.CURRENT_USER_ID.getMessage());
    }
}
